package com.example.conversionpx;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private Button btn1,btn2;
    private EditText et1,et2,et11,et22;
    private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.context=getApplicationContext();
        btn1=findViewById(R.id.bt1);
        btn2=findViewById(R.id.bt12);
        et1=findViewById(R.id.et1);
        et2=findViewById(R.id.et2);
        et11=findViewById(R.id.et11);
        et22=findViewById(R.id.et22);
    }

    public void toonclick1(View view) {
        String s1 = et1.getText().toString();
        float a=Float.parseFloat(s1);
        int i = px2dip(context, a);
        et2.setText(String.valueOf(i));
    }

    public void toonclick2(View view) {
        String s2 = et11.getText().toString();
        float a=Float.parseFloat(s2);
        int ii = dip2px(context, a);
        Log.e("sasasas", String.valueOf(ii));
        et22.setText(String.valueOf(ii));
    }


    //把String转化为float
    public static float convertToFloat(String number, float defaultValue) {
        if (TextUtils.isEmpty(number)) {
            return defaultValue;
        }
        try {
            return Float.parseFloat(number);
        } catch (Exception e) {
            return defaultValue;
        }

    }
    /**
     * 根据手机的分辨率从 dip 的单位 转成为 px(像素) 转换
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}